package com.haierp.service.impl;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.google.common.collect.Lists;
import com.haierp.mapper.ItemMapper;
import com.haierp.model.Inventory;
import com.haierp.model.Item;
import com.haierp.model.ItemSku;
import com.haierp.model.PackageLevel;
import com.haierp.service.IBrandService;
import com.haierp.service.IFreightService;
import com.haierp.service.IInventoryService;
import com.haierp.service.IItemService;
import com.haierp.service.IItemSkuService;
import com.haierp.service.IUploadFileService;
import com.haierp.service.item.IOuterItemService;
import com.haierp.util.JsonPageResult;
import com.haierp.util.JsonResult;
import com.haierp.vo.ItemQueryVO;
import com.haierp.vo.ItemSkuQueryVO;

@Service("itemService")
public class ItemServiceImpl extends SuperServiceImpl<ItemMapper, Item>implements IItemService {
    protected Logger logger = LogManager.getLogger(getClass());

	@Autowired
	private IItemSkuService itemSkuService;
	
	@Autowired
	private IFreightService iFreightService;
	
	@Autowired
	private IInventoryService inventoryService;
	
	@Autowired
	private IBrandService iBrandService;
	
	@Autowired
	private IOuterItemService outerItemService;
	
	@Autowired
	private IUploadFileService uploadFileService;

	@Override
	public void addItem(Item item) {
		this.baseMapper.insertSelective(item);
		
		List<ItemSku> itemSkuList = item.getItemSkus();
		if (itemSkuList != null && !itemSkuList.isEmpty()) {
			itemSkuList.forEach(itemSku -> {
				itemSku.setItemCode(item.getItemCode());
				itemSku.setItemName(item.getName());
				itemSku.setItemId(item.getId());
				itemSku.setCategoryId(item.getCategoryId());
				itemSku.setCategoryName(item.getCategoryName());
				itemSku.setBrand(item.getBrand());
				skuFreight(itemSku);
			});
			itemSkuService.insertBatch(itemSkuList);
			List<Inventory> inventoryList = itemSkuService.initInventory(itemSkuList);
			inventoryService.insertBatch(inventoryList);
		}
	}

	//计算当前SKU的运费
	private void skuFreight(ItemSku itemSku) {
		Double packageWeight=0.0d;
		//1,获取包装重量
		if(itemSku.getPackageId()!=null){
			PackageLevel pl=	iFreightService.getPackageLevel(itemSku.getPackageId());
			if(pl==null){
				return;
			}else{
				packageWeight = pl.getWeight();
				itemSku.setPackageWeight(packageWeight);
				itemSku.setPackageEn(pl.getPackageEn());
				itemSku.setPackageName(pl.getName());
			}
		}
		Double itemWeight = 0.0d;
		
		if(itemSku.getWeight()!=null){
			itemWeight = itemSku.getWeight();
		}
//		if(itemSku.getPackageWeight()!=null){
//			packageWeight = itemSku.getPackageWeight();
//		}
		Long f = iFreightService.calculateFreight(itemWeight, packageWeight);
		itemSku.setFreight(f);
	}

	@Override
	public void updateItem(Item item) {
		this.baseMapper.updateSelectiveById(item);
				
		List<ItemSku> itemSkuList = item.getItemSkus();
		List<ItemSku> itemSkuListNew = new ArrayList<>(); //新增的SKU
		List<ItemSku> itemSkuListUpdate = new ArrayList<>();//修改的SKU
		//获取数据库里面的所有sku
		ItemQueryVO itemQueryVO = new ItemQueryVO();
		itemQueryVO.setItemId(item.getId());
		Item itemDb = queryItem(itemQueryVO);
		List<ItemSku> itemSkuListDb = itemDb.getItemSkus();
		Set<Long> allSkus = new HashSet<Long>();
		if(itemSkuListDb!=null&&!itemSkuListDb.isEmpty()){
			itemSkuListDb.forEach(itemSku->{ allSkus.add(itemSku.getId()); });
		}
		itemSkuList.forEach(itemSku -> {
			if(itemSku.getId()==null){
				itemSkuListNew.add(itemSku);
			}else{
				if(!allSkus.isEmpty()){
					allSkus.remove(itemSku.getId());
				}
				itemSku.setGmtModify(new Date());
				itemSkuListUpdate.add(itemSku);
			}
			skuFreight(itemSku);
		});
		if(!itemSkuListUpdate.isEmpty()){
			itemSkuService.updateBatchById(itemSkuListUpdate);
			List<ItemSku> newInvList = Lists.newArrayList();
			for(ItemSku itemSku:itemSkuListUpdate){
				Inventory inventory = inventoryService.queryInventoryBySkuId(itemSku.getItemId(), itemSku.getId());
				if(inventory==null){
					newInvList.add(itemSku);
				}else{
					if(inventory.getVirtualInv()!=itemSku.getVirtualInv()){
						inventory.setVirtualInv(itemSku.getVirtualInv());
						inventory.setGmtModify(new Date());
						inventoryService.updateById(inventory);
					}
				}
			}
			if(CollectionUtils.isNotEmpty(newInvList)){
				List<Inventory> inventoryList = itemSkuService.initInventory(newInvList);
				inventoryService.insertBatch(inventoryList);
			}
			
		}
		if(!itemSkuListNew.isEmpty()){
			itemSkuService.insertBatch(itemSkuListNew);
			List<Inventory> inventoryList = itemSkuService.initInventory(itemSkuListNew);
			inventoryService.insertBatch(inventoryList);
		}
		if(!allSkus.isEmpty()){
			//itemSkuService.deleteBatchIds(new ArrayList<Long>(allSkus));
			//先判断sku是否可以删除
			allSkus.forEach(skuId -> {
				itemSkuService.deleteSkuById(skuId);
			});
		}
	}

	@Override
	public Item queryItem(ItemQueryVO itemQueryVO) {
		if(itemQueryVO.getItemId()==null){
			throw new RuntimeException("the item id is null");
		}
		Item item = this.baseMapper.selectById(itemQueryVO.getItemId());
		if(item!=null){
//			Map<String,Object> clumnMap = new HashMap<>();
//			clumnMap.put("item_id", id);
			List<ItemSku> itemSkus = itemSkuService.queryItemSkusByItemId(itemQueryVO);
			/*boolean flage = false;
			for (ItemSku itemSku : itemSkus) {
			     if(StringUtils.isNotBlank(itemSku.getUpc()) && itemSku.getInventory() == 0) {
			    	 flage = true;
			    	 itemSku.setIfSaleCount(1);
			     } else{
			    	 itemSku.setIfSaleCount(0);
			     }
			}
			ListSort(flage,itemSkus);// 多重排序优先按照 upc排序
*/			if(itemSkus!=null){
				item.setItemSkus(itemSkus);
			}
		}
		return item;
	}

	@Override
	public JsonPageResult<List<Item>> queryItems(ItemQueryVO itemQueryVO) {
		JsonPageResult<List<Item>> itemResult = new JsonPageResult<>();
		//1、查询总的记录数量
		Integer totalCount =  this.baseMapper.queryItemsCount(itemQueryVO);
		
		//2、查询分页记录
		if(totalCount!=null&&totalCount!=0){
			itemResult.buildPage(totalCount, itemQueryVO);
			List<Item> items = this.baseMapper.queryItems(itemQueryVO);
			itemResult.setData(items);
		}else{
			List<Item> items  = new ArrayList<>();
			itemResult.setData(items);
		}
		return itemResult;
	}
	
	@Override
	public JsonPageResult<List<Item>> queryItemBuySite(ItemQueryVO itemQueryVO) {
		JsonPageResult<List<Item>> itemResult = new JsonPageResult<>();
		//1、查询总的记录数量
		Integer totalCount =  this.baseMapper.queryItembuySiteCount(itemQueryVO);
		
		//2、查询分页记录
		if(totalCount!=null&&totalCount!=0){
			itemResult.buildPage(totalCount, itemQueryVO);
			List<Item> items = this.baseMapper.queryItembuySite(itemQueryVO);
			itemResult.setData(items);
		}else{
			List<Item> items  = new ArrayList<>();
			itemResult.setData(items);
		}
		return itemResult;
	}

	@Override
	public JsonResult<List<Item>> queryItembuySiteNoPaging(ItemQueryVO itemQueryVO) {
		JsonResult<List<Item>> itemResult = new JsonResult<>();
		List<Item> items = this.baseMapper.queryItembuySiteNoPaging(itemQueryVO);
		itemResult.setData(items);
		return itemResult;
	}

	@Override
	public List<Item> queryItems(List<Long> ids) {
		return this.baseMapper.selectBatchIds(ids);
	}

	/**
	 * 获取所有的 ItemCode and Id
	 * 2017-04-04,jc
	 */
	@Override
	public Map<String, Long> queryAllItemCodeAndIdHashMap() {
		List<Map<String, Object>> codeAndIdMap = this.baseMapper.queryAllItemCodeAndIdHashMap();
		Map<String, Long> result = new HashMap<String,Long>();

		String itemCode = null;
		Long id = null;
		for (Map<String, Object> map : codeAndIdMap) {
			itemCode = null;
			id = null;
			
			for (Map.Entry<String, Object> entry : map.entrySet()) {
				if ("id".equals(entry.getKey())) {
					id = ((Long)entry.getValue());
				} else if ("itemCode".equals(entry.getKey())) {
					itemCode = ((String)entry.getKey());
				}
			}
			result.put(itemCode, id);
		}
		
		return result;
	}

	@Override
	public String insertIntoItemDimension(String sceneStr, String pages, String accessToken) {
		RestTemplate rest = new RestTemplate();
		InputStream inputStream = null;
		OutputStream outputStream = null;
		String picUrl = null;
		try {
			String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
			Map<String, Object> param = new HashMap<>();
			param.put("scene", sceneStr);
			param.put("page", pages);
			param.put("width", 430);
			param.put("auto_color", false);
			Map<String, Object> line_color = new HashMap<>();
			line_color.put("r", 0);
			line_color.put("g", 0);
			line_color.put("b", 0);
			param.put("line_color", line_color);
			MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
			HttpEntity requestEntity = new HttpEntity(param, headers);
			ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class,
					new Object[0]);
			System.err.println("调用生成微信URL接口传参:" + entity.getBody());
			byte[] result = entity.getBody();
			inputStream = new ByteArrayInputStream(result);

			StringBuilder sb = new StringBuilder();
			sb.append((int) (Math.random() * 100)).append("_").append(System.currentTimeMillis()).append(".")
					.append("jpg");
			String picKey = sb.toString();
			picUrl = uploadFileService.uploadImg(inputStream, picKey);
			if (picUrl.isEmpty()) {
				throw new RuntimeException("二维码生成异常！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("调用生成微信URL接口传参:" + e);
			// LOG.error("调用小程序生成微信永久小程序码URL接口异常",e);
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return picUrl;

	}

	@Override
	public JsonPageResult<List<Item>> queryHaihuItems(ItemQueryVO itemQueryVO) {
		JsonPageResult<List<Item>> itemResult = new JsonPageResult<>();
		//1、查询总的记录数量
		Integer totalCount =  this.baseMapper.queryItemsCountByhaihu(itemQueryVO);
		
		//2、查询分页记录
		if(totalCount!=null&&totalCount!=0){
			itemResult.buildPage(totalCount, itemQueryVO);
			List<Item> items = this.baseMapper.queryHaihuItems(itemQueryVO);
			itemResult.setData(items);
		}else{
			List<Item> items  = new ArrayList<>();
			itemResult.setData(items);
		}
		return itemResult;
	}



	@Override
	public List<Item> queryHaihuByUptime(ItemQueryVO itemQueryVO) {
		List<Item> items = this.baseMapper.queryHaihuByUptime(itemQueryVO);
		return items;
	}

	@Override
	public JsonPageResult<List<Item>> responsePurchaseDetailToSaler(ItemQueryVO itemQueryVO) {
		JsonPageResult<List<Item>> itemResult = new JsonPageResult<>();
		//1、查询总的记录数量
		Integer totalCount =  this.baseMapper.responsePurchaseCount(itemQueryVO);
		
		//2、查询分页记录
		if(totalCount!=null&&totalCount!=0){
			itemResult.buildPage(totalCount, itemQueryVO);
			List<Item> items = this.baseMapper.responsePurchaseDetailToSaler(itemQueryVO);
			itemResult.setData(items);
		}else{
			List<Item> items  = new ArrayList<>();
			itemResult.setData(items);
		}
		return itemResult;
	}
	
	private static void ListSort(boolean flage, List<ItemSku> list) {
		if(flage) {
			Collections.sort(list, new Comparator<ItemSku>() {
				@Override
				public int compare(ItemSku o1, ItemSku o2) {
					int dt1 = o1.getIfSaleCount();
					int dt2 = o2.getIfSaleCount();
					if (dt1 > dt2) {
						return -1;
					} else if (dt1 < dt2) {
						return 1;
					} else {
						return 0;
					}
				}
			});
		} else {
			Collections.sort(list, new Comparator<ItemSku>() {
				@Override
				public int compare(ItemSku o1, ItemSku o2) {
					int dt1 = o1.getVirtualInv();
					int dt2 = o2.getVirtualInv();
					if (dt1 > dt2) {
						return -1;
					} else if (dt1 < dt2) {
						return 1;
					} else {
						return 0;
					}
				}
			});
		}

	}

	@Override
	public void updateAllOldBuySiteByitem(ItemSkuQueryVO itemSkuQueryVO) {
		this.baseMapper.updateAllOldBuySiteByitem(itemSkuQueryVO);
	}
}
